package cn.thens.kdroid.core.storage

import android.content.SharedPreferences

internal class PreferencesStorage(private val prefs: SharedPreferences) : Storage<String, String> {
    override fun node(key: String): Storage.Node<String> {
        return Node(prefs, key)
    }

    override fun clear() {
        prefs.edit().clear().apply()
    }

    override fun getAll(): Map<String, String> {
        return prefs.all.mapValues { it.value.toString() }
    }

    override fun getKeys(): Set<String> {
        return prefs.all.keys
    }

    class Node(private val prefs: SharedPreferences, private val key: String) : Storage.Node<String> {

        override fun get(): String {
            return prefs.getString(key, null)!!
        }

        override fun put(value: String) {
            prefs.edit().putString(key, value).apply()
        }

        override fun clear() {
            prefs.edit().remove(key).apply()
        }

        override fun exists(): Boolean {
            return prefs.contains(key)
        }
    }
}
